﻿
layui.use(['form'], function(){
    	//element = layui.element;
     var  form = layui.form;
       //table = layui.table;
     var  layer = layui.layer;

    /*
     自定义查询条件
     1, layui 会自动以键值对json格式收集 layui-form定义下面所有的checkbox，input，select 选中值的name和value。
     2, 提交方式 form.on('submit(formDemo)', function(data){  })   formDemo为按钮上定义 lay-filter="formDemo"。
     3，其他特殊参数，提交时，可以以 data.field.other = "test";  这种json追加参数方式，并入上面说明2的集合里来。 ohter为参数名，test为值
     4，如还有其他特殊情况，联系前端人员进行修改，补充，完善。
     */
    $.fn.searchGroup = function(options, callback){
    	//默认参数
        var defaluts = {
            data: '',
            rows:4,  //每行显示个数
    		placeholder:false
        };

        var settings = $.extend({}, defaluts, options); 
    	var rows = parseInt(12/settings.rows);

        this.each(function() {
            var dataLength = settings.data.length;
            var item = '';
    		var _this = $(this);
    		
    			item += '<form class="layui-row layui-form" action="">';
            
            //循环数据
            $.each(settings.data, function(index, el) {	
    		   //判断是否显示placeholder
    		   if(settings.placeholder == true){
    			  var placeholder = '请输入' + el.text
    		   } else {
    			  var placeholder = ''
    		   };

               
               //拼接搜索项dom
    		   if(index >= settings.rows -1){ //初始化隐藏后面查询项
    			  item += '<div class="layui-col-md'+ rows +'" style="display:none">';
    		   } else {
    			  item += '<div class="layui-col-md'+ rows +'">';
    		   }
               item += '<label class="layui-form-label">'+ el.text +':</label>';
               item += '<div class="layui-input-block">';

    		   //没有type类型
    		   if(!el.type || el.type == ''){
    			       item += '<input type="text" name="'+ el.value +'" placeholder="'+ placeholder +'" autocomplete="off" class="layui-input">';
    		   };

               switch(el.type){
                    case 'input':
                        item += '<input type="text" name="'+ el.value +'" placeholder="'+ placeholder +'" autocomplete="off" class="layui-input">';
                    break;
    				case 'date': //日期id参数单独以 dateid 命名
                        item += '<input type="text" name="'+ el.value +'" placeholder="'+ placeholder +'" id="'+ el.dateid +'" autocomplete="off" class="layui-input layui-date">';
                    break;
    				case 'select':
                        item += '<select name="'+ el.value +'" id="'+ el.value +'"  lay-filter="'+ (!el.layFilter ? el.value : el.layFilter) +'">';
                        $.each(el.child, function(i, e) {
                             item += '<option value='+ e.value +'>'+ e.text +'</option>'
                        });
                        item += '</select>';
                    break;
                    case 'radio':
                        $.each(el.child, function(i, e) {
    						if(e.checked && e.checked == true){
    							 item += '<input type="radio" name="'+ el.value +'" value="'+ e.value +'" title="'+ e.text +'" checked>'
    						} else {
    							item += '<input type="radio" name="'+ el.value +'" value="'+ e.value +'" title="'+ e.text +'">'
    						}
                             
                        });
                    break;
    				case 'checkbox':
                        $.each(el.child, function(i, e) {
    						if(e.checked && e.checked == true){
    							 item += '<input type="checkbox" lay-skin="primary" name="'+ el.value +'" value="'+ e.value +'" title="'+ e.text +'" checked>'
    						} else {
    							item += '<input type="checkbox" lay-skin="primary" name="'+ el.value +'" value="'+ e.value +'" title="'+ e.text +'">'
    						}
                        });
                    break;
                };
    			item += '</div>';
                item += '</div>';
            });

    			item += '</form>';

            //载入对象dom中
            $(this).html(item)
    		
    		//查询按钮载入
    		var btnDom ='<div class="layui-col-md'+ rows +' layui-col-md-offset'+ rows +'" style="text-align:right" id="cx">';
    		 	btnDom += '<div class="layui-input-inline">';
                btnDom += '<button class="layui-btn" lay-submit lay-filter="filterForm">查 询</button>';
    			btnDom += '<button type="reset" class="layui-btn layui-btn-primary">重 置</button>';
    			if(dataLength > 3){ //大于3个条件项才出现展开
    				btnDom += '<a href="javascript:void(0)" class="ad-unfold">展开<i class="layui-icon">&#xe61a;</i></a>';
    			}
                btnDom += '</div>';
    			btnDom += '</div>';
    			

            //查询按钮所放位置
			//console.log(dataLength)
			if(dataLength < 3){
				$(this).children('form').children('div:last-child').after(btnDom)
			} else {
				$($(this).children('form').children('div').eq(settings.rows == 5 ? (settings.rows - 1): (settings.rows -2))).after(btnDom);
			}
    		
    		//回调处理
    		if(typeof callback === 'function'){
    			callback()
    		}

            //selec,checkbox,radio重新渲染
            form.render()


    		//显示展开隐藏项
    		$("#searchGroup").on('click', '.ad-unfold', function(event) {
                var ele = $(this).parent().parent();
    			var moveEle = _this.children('form').children('div').eq(dataLength);
                if($(this).html().indexOf('展开') != -1){ //展开
                    $(this).html('折叠<i class="layui-icon">&#xe619;</i>');
    				$(ele).nextAll().not(".rele").show()
    				
    				//展开后改变查询按钮的方位
    				$(ele).insertAfter(moveEle)
    				
                } else { //折叠

                    $(this).html('展开<i class="layui-icon">&#xe61a;</i>');
    				$(ele).nextAll().not(".rele").hide()
    				
    				//折叠后隐藏多余查询项
    				_this.children('form').children('div').eq(settings.rows -2).nextAll().css("display","none")
    				$(ele).insertAfter(_this.children('form').children('div').eq(settings.rows -2)).css("display","block");
                }
            });

        })
    };



 /*
     自定义操作按钮
     */
    $.fn.tableDataBtn = function(options, callback){
        //默认参数
        var defaluts = {
            data: '',
            btnStyle:'layui-batch-action', //按钮颜色
            icon:'&#xe654;', //按钮前图标配置
            id:'add' //按钮id，可用作事件触发
        };

        var settings = $.extend({}, defaluts, options); 
        var length = settings.batchData.length; //批量操作项只有一个的时候


        this.each(function() {
            var btnStr = '';
            var batchBtnStr = '';
            //var length = settings.batchData; //批量操作按钮

			//操作项按钮
            $.each(settings.data, function(index, el) {
                btnStr += '<button type="button" class="layui-btn '+ (el.btnStyle?el.btnStyle:settings.btnStyle) +'" id='+ el.id +' data-type="'+ el.dataType +'"><i class="layui-icon">'+ el.icon +'</i>'+ el.name +'</button>';
            });

			//批量操作按钮
            batchBtnStr += '<div id="tableBatchBtn">';
            if(length == 1){ //只有一个批量处理按钮的时候
                batchBtnStr += '<a href="javascript:void(0)" class="layui-btn layui-batch-action layui-btn-primary" data-type="'+ settings.batchData[0].dataType +'" id='+ settings.batchData[0].id +'><i class="layui-icon">'+ settings.batchData[0].icon +'</i>'+ settings.batchData[0].name +'</a>';
            } else {
                batchBtnStr += '<div class="batch_element_hd">批量操作 <i class="layui-icon">&#xe61a;</i></div>';
				batchBtnStr += '<div class="batch_element_bd">';
				$.each(settings.batchData, function(i, ele) {
	                batchBtnStr +=  '<a href="javascript:void(0)" class="layui-btn layui-batch-action" data-type="'+ ele.dataType +'" id='+ ele.id +'><i class="layui-icon">'+ ele.icon +'</i>'+ ele.name +'</a>'
	            });
				batchBtnStr += '</div>';
            }
            batchBtnStr += '</div>';

            $(this).html(btnStr)
            $(this).after(batchBtnStr)
			//tool
			$.operPrimary()
        })
    };




    //图标菜单插件 //目前只支持 Unicode 和 Fontclass 两种方式
    $.fn.iconfont = function(options){
          //默认参数
          var defaluts = {
              pageUrl: '../systemMenu/iconfont', //图标代码页面的路径
              fillid:'#menuStyle', //装载图标代码的input容
          };

          var settings = $.extend({}, defaluts, options); 

          this.each(function() {
              var _this = $(this);
              
              //如果是编辑窗口，初始化加载默认图标
              if(_this.val()!=''){
    				$(".seticon").remove();
                    _this.after("<div style='padding-left:5px; font-size:20px;float:right; margin-top:-27px; margin-right:5px; position: relative; z-index:100' class='seticon icon iconfont "+ _this.val() +"'></div>");
              }

              _this.on('click', function() {
    	
    			 //图标选择界面 注：弹窗必须基于layui layer组件支持 
                  parent.layer.open({
                      type:2,
                      title:'配置图标菜单',
                      area:['80%', '80%'],
                      content:settings.pageUrl,
                      success: function(layero, index){
    						//获取弹窗
                            var body =  parent.layer.getChildFrame('body', index);
    						//改写iconfont页面展示样式
    						body.find(".icon").css("height","50px");
    						body.find(".nav-tabs,.markdown").hide()
                            body.find(".tab-container>div").eq(0).hide()
                            body.find(".tab-container>div").eq(1).show();
    						body.find(".dib").css({
    							    'width': '100px',
    							    'margin-bottom': '10px',
    							    'margin-right': '20px',
    							    'text-align': 'center',
    								'float': 'left',
    								'font-size': '14px',
    								'height': '150px',
    						});
    						body.find(".name, .code-name").css({
    							'display': 'block',
    						    'width': '100%',
    						    'height': '20px',
    						    'line-height': '20px',
    						    'color': '#666',
    						    'font-size': '12px',
    						    'text-align': 'center',
    						    'margin-top': '5px',
    						    'overflow': 'hidden',
    						    'white-space': 'nowrap',
    						    'text-overflow': 'ellipsis',
    						})


    						function iGetInnerText(testStr) {
    					        var resultStr = testStr.replace(/\ +/g, ""); //去掉空格
    					        resultStr = testStr.replace(/\s/g, "");    //去掉空格
    					        return resultStr;
    					    }

                            //iconfont页面循环，找出对应的图标高亮
                            $.each(body.find(".tab-container>div").eq(1).find('.code-name'), function(index, el){
    							if(iGetInnerText($(el).html()) == '.'+_this.val()){
    								$(el).css("color","red");
                                    $(el).prev().css("color","red");
    								$(el).prev().prev().css("color","red");
    							}
                            })

    						
    						//点击获取图标
    					    body.find('.icon_lists').on('click', 'li', function(event) {
    							var name = $(this).find('.name').text();
    							var codename = $(this).find('.code-name').text();
    							$(".seticon").remove();
    							
                                //展示图标
                                 _this.after("<div style='padding-left:5px; font-size:20px;float:right; margin-top:-27px; margin-right:5px; position: relative; z-index:100' class='seticon icon iconfont "+ codename.split('.')[1] +"'></div>")
    							parent.layer.close(index); //执行关闭弹窗  

                                //设置value 
                                $(settings.fillid).val(codename.split('.')[1]); //设置图标代码 font class
    							
                            });

                      }
                  })

              });
          });
    };


     $.extend({
				//隐藏批量操作按钮
				hideBatchBtn: function(_this){
					if(!_this){
						var _this = $("#tableBatchBtn")
					}
					$(_this).hide()
				},
            	//操作项目
                operPrimary: function(id,p_layer){
                    if(!id){
                        id = '.demoTable';
                    }
                    var layers;
                    if(p_layer){
                    	layers = p_layer;
                    }else{
                    	layers = layui.layer;
                    }
                    var element = '';
					    element += '<div id="tableTool">';	
                        element += '<a href="javascript:void(0)" class="layui-batch-action" data-tips="密度" data-type="columnHeight"><i class="iconfont">&#xe790;</i></a>';
                        element += '<a href="javascript:void(0)" class="layui-batch-action" data-tips="全屏" data-type="fullscreen"><i class="iconfont">&#xe743;</i></a>';
                        element += '<a href="javascript:void(0)" class="layui-batch-action" data-tips="刷新" data-type="refresh"><i class="iconfont">&#xe64d;</i></a>';
                        element += '<a href="javascript:void(0)" class="layui-batch-action" style="display: none;" data-tips="刷新" data-type="getCheckData"><i class="iconfont">&#xe64d;</i></a>';
						element += '</div>';

                    $(id).append(element)


                    //鼠标经过tips
                    $(".layui-batch-action").hover(function(){
                        if($(this).data('tips')){
                            layers.tips($(this).data('tips'), $(this), {tips:1});
                        }
                    })
                    
                },
                //表格密度调整
                columnHeight: function(){
                     $(".ad-table-card .layui-table-view").toggleClass('ad-table-small')
                },
                //表格全屏
                fullscreen: function(id, tab){
                    var element = document.getElementById(id);
                        if (element.mozRequestFullScreen) {
                          element.mozRequestFullScreen();
                        } else if (element.webkitRequestFullScreen) {
                          element.webkitRequestFullScreen();
                        }
                        location.reload()
                },
    			//table checkbox计数
    			checkboxNum: function(num){
    				  num == undefined ? num = '0' : num = num;	
    				  if($(".layui-table-alert .layui-table-title").length == 1){
    					$(".layui-table-alert em").html(num);
    					return false;
    				  }

					  //console.log(num)
					  if($(".layui-table-alert").length == 1){
						  $(".layui-table-alert em").html(num);
						  return false;
					  }
    				  $('#ad-table-card .layui-card-header').append('<div class="layui-table-alert"><span class="l"><i class="iconfont">&#xe659;</i> 已选择 <em>'+ num +'</em> 项</span></div>')
    			},
                //工具操作集合
                actionFun:function(tab, actives,p_form,p_table) {
                	var forms,tables;
                    if(p_form){
                    	forms = p_form;
                    }else if(form){
                    	forms = form;
                    }else{
                    	
                    	forms = layui.form;
                    }
                    if(p_table){
                    	tables = p_table;
                    }else{
                    	tables = layui.table;
                    }
                    var active = {
                        //checkbox选中项
                        getCheckData: function(){
                            var checkStatus =  tables.checkStatus(tab.config.id);
                            var data = checkStatus.data;
    						
    						$.checkboxNum(data.length)

                            //是否隐藏显示批量操作工具
                            if(checkStatus.data  != ''){
                                $("#tableBatchBtn").show()
                            } else {
                                $('#tableBatchBtn').hide()
                            }
                        }
                        //刷新表格
                        ,refresh: function() {
                        	 $(".layui-table-alert em").html(0);
                            tab.reload();
                           
                        }
                        //表格密度调整
                        ,columnHeight: function() {
                            $.columnHeight();
                        }
                        //全屏
                        ,fullscreen: function(){
                            $.fullscreen('ad-table-card', tab)
                        }
                    };

                    var obj = $.extend(active, actives); //参数合并

                    //操作点击项
                    $('.demoTable .layui-batch-action').on('click', function () {
                        var type = $(this).data('type');
                        active[type] ? active[type].call(this) : '';
                    });


                    //表格checkbox单选触发
                    $("body").on('click',".layui-form-checkbox", function(event) {
                        active['getCheckData'] ? active['getCheckData'].call(this) : '';

                        //全选反选的判断
    					var checkboxLength = $("input[name=layTableCheckbox]").length -1;
                        var checkboxedLength = $(".layui-table-body input[name=layTableCheckbox]:checked").length;
    					var layAll;
    					$.each($("input[name=layTableCheckbox]"), function(index, el){
    						if($(el).attr("lay-filter") == 'layTableAllChoose'){
    							layAll = el;
                            }
    					})
	
    					if(checkboxLength == checkboxedLength){
                             $(layAll).prop("checked","checked")
                        } else {
    						 $(layAll).prop("checked","")
    					}
    					form.render("checkbox")
                    });

                    
                    //表格checkbox全选触发
                    forms.on('checkbox(layTableAllChoose)', function(data){
                        setTimeout(function(){
                            active['getCheckData'] ? active['getCheckData'].call(this) : '';
                        },300)
                    })
                }
     
     } );
   
   

    /*
        init
    */

    $(function(){
        var getNav = JSON.parse(sessionStorage.getItem("nav"));  
    	if(getNav == null){
			return false;
		}
    	//面包屑对应加载菜单名称
        if(getNav.parentName == undefined || getNav.parentName == null){
            getNav.parentName = ''
        } else {
            getNav.parentName = '<a href="">'+ getNav.parentName +'</a>'
        }
        $("#crumbs").removeClass('layui-breadcrumb').html('<i class="layui-icon">&#xe715;</i> '+ '<a href="">'+ getNav.parentsName +'</a>' + getNav.parentName +'  <a>'+ getNav.thisName +'</a>')

    	//checkbox计数初始化
    	setTimeout(function(){
			try{
				if($($("#ad-table-card table")[1]).find("input[type=checkbox]").length == 1){
        			$.checkboxNum(0)
        		}
				//var x = tab;
			}catch(e){
				if($($("#ad-table-card table")[1]).find("input[type=checkbox]").length == 1){
        			$.checkboxNum(0)
        		}
			}
    	},300)
    	
    })


    /*
      左侧折叠菜单 start
     */

   function fold(_this){
        
        if(_this.hasClass('show')){ //折叠
            _this.removeClass('show');
            _this.find('i').html('&#xe602;');

            $(".layui-side").animate({
            	left: '0'
            });
            $(".menu-fold, .layui-body, .layui-header").animate({
            	left: '256px'
            });

        } else { //展开
            _this.addClass('show'); 
            _this.find('i').html('&#xe603;');

            $(".layui-side").animate({
            	left: '-256px'
            });
            $(".menu-fold, .layui-body, .layui-header").animate({
            	left: '0px'
            });
        }
    //});
  }

  //二级左侧菜单折叠效果
    $("body").on('click', '.menu-fold', function(event) {
    	fold($(this))
    })


});